import datetime, asyncio, aiohttp, json, logging, os.path, os, encodings.idna

# 设置打印日志文件
logger = logging.getLogger()
logger.setLevel(logging.INFO)  # Log等级总开头
rq = datetime.datetime.now().strftime('%Y%m%d')
# log_path = os.path.dirname(os.getcwd()) + '/logs/'
log_path = './logs/'
log_name = log_path + rq + '.log'
logfile = log_name
fh = logging.FileHandler(logfile, mode='a')
fh.setLevel(logging.INFO)  # 输出到file的log等级的开头
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
logger.addHandler(fh)
# 设置打印日志结束

# 定义初始化变量，可以通过confHttp.ini文件重新定义变量值
url = "http://wwww.baidu.com/"
highCount = 5           # 限制并发量
semaphoreCount = 2      # 总共任务
diffTotal = 0           # 总时间差
requestDateParam = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') # 当前请求日期
performIdParam = "RQ" + datetime.datetime.now().strftime('%Y%m%d%H%M%S') # 当前请求ID
requestTypeParam = '轮询'


with open("confHttp.ini", "r", encoding="utf-8") as f:
    data = json.load(f)
    if len(data) != '':
        for line in data:
            url = line['url']
            highCount = line['highCount']
            semaphoreCount = line['semaphoreCount']
            requestTypeParam = line['requestType']


async def getUrl(url, semaphore):
    startDate = datetime.datetime.now()
    async with semaphore:
        async with aiohttp.ClientSession() as session:
            global performIdParam
            global requestDateParam
            global requestTypeParam
            async with session.post(url, data={"performId": performIdParam, "requestDate": requestDateParam, "requestType": requestTypeParam}) as response:
                endDate = datetime.datetime.now()
                diffSeconds = (endDate - startDate).seconds
                global diffTotal
                diffTotal += diffSeconds
                
                print('开始请求:%s' % startDate.strftime('%Y-%m-%d %H:%M:%S'))
                print('结束请求:%s' % endDate.strftime('%Y-%m-%d %H:%M:%S'))
                print('时间差:%s' % diffSeconds)
                print('----------------------------------')
                logger.info('开始请求:%s' % startDate.strftime('%Y-%m-%d %H:%M:%S'))
                logger.info('结束请求:%s' % endDate.strftime('%Y-%m-%d %H:%M:%S'))
                logger.info('时间差:%s' % diffSeconds)
                logger.info('----------------------------------')
                return await response.read()


async def run():
    semaphore = asyncio.Semaphore(semaphoreCount)  # 限制并发量
    to_get = [getUrl(url.format(), semaphore) for _ in range(highCount)]  # 总共highCount任务
    await asyncio.wait(to_get)



if __name__ == '__main__':
    print('**开始==================================================================')
    logger.info('**开始==================================================================')
    loop = asyncio.get_event_loop()
    loop.run_until_complete(run())
    loop.close()
    logger.info('总耗时为: %d 秒' % diffTotal)
    logger.info('结束==================================================================')
    logger.info('')
    print('总耗时为: %d 秒' % diffTotal)
    print('结束==================================================================')
    #os.system("pause")
